"""
@project: PyCharm
@author: MZM
@file: tasks.py
@ide: PyCharm
@time: 2021/7/16 19:31
@desc： 
"""
import datetime
import os
import socket
from celery import shared_task
from django.core.files import File
from ruamel import yaml

from .models import TESTREPORT
from .runner.testrunner import run
import logging

logger = logging.getLogger(__name__)
filedir = os.path.dirname(__file__)
ip = socket.gethostbyname(socket.gethostname())
if os.path.exists(f'./runner/data/'):
    os.mkdir(f'./runner/data/')

def run_task(testdata):
    with open(filedir + f'/runner/data/test.yaml', 'w', encoding='utf-8') as f:
        yaml.dump(testdata, f, Dumper=yaml.RoundTripDumper)
    reportdir = run()
    with open(reportdir + '/index.html', 'r', encoding='utf-8') as f:
        thisfile = File(f)
        thisfile.name = thisfile.name.split('testreport/')[1]
        testreport = TESTREPORT.objects.create(reportname=datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '测试报告', reportfile=thisfile, result='Y')
    return {'msg':'succees'}

@shared_task
def runstep_task(teststeps):
    return run_task([teststeps])

@shared_task
def runtestcase_task(testcases):
    return run_task(testcases)

@shared_task
def runtestsuite_task(mode,testsuite):
    return run_task(testsuite)